<?php

namespace Modules\Xunsearch\Library;

use Core\Mvc\Entity\EntityInterface;
use Modules\Queue\Library\Queue;
use Phalcon\Di;
use Phalcon\Events\Event;

class EntityListener
{
    public function editForm(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'config' && $entity->getId() == 'search.settings') {
            $field = $entity->getField();
            $searchFieldHook = Di::getDefault()->getShared('config')->get('xunsearch.searchSettings');
            $field = array_merge($field, $searchFieldHook);
            $entity->setField($field);
        }
    }

    public function saveBefore(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'config' && $entity->getId() == 'search.settings') {
            $request = Di::getDefault()->getShared('request');
            //删除配置文件
            if ($request->hasPost('xunsearch')) {
                $xunsearch = $request->getPost('xunsearch');
                foreach ($xunsearch as $item) {
                    $filePath = CONFIG_DIR . 'modules/xunsearch/' . strtolower($item) . '.ini';
                    if (file_exists($filePath)) {
                        unlink($filePath);
                    }
                }
            }

            //重建索引
            if ($request->hasPost('xunsearch_rebuild')) {
                $xunsearchRebuild = $request->getPost('xunsearch_rebuild');
                if (!empty($xunsearchRebuild)) {
                    $queue = new Queue();
                    $queue->add('xunsearchRebuild', $xunsearchRebuild);
                }
            }
        }
    }

    public function saveAfter(Event $event, EntityInterface $entity)
    {
        $field = $entity->getField();
        $options = $field['_options'];
        if (isset($options['xunsearch'])) {
            $data = [];
            $xunsearch = new Xunsearch($options['xunsearch']);

            foreach ($xunsearch->getConfig()->toArray() as $name => $value) {
                if (is_array($value) && (isset($value['type']) || isset($value['index'])) && $name != 'id') {
                    $data[$name] = is_string($entity->{$name}) ? strip_tags($entity->{$name}) : implode(',', objectToArray($entity->{$name}));
                }
            }
            $data['id'] = (string) $entity->getId();
            $xunsearch->update($data);
        }
    }

    public function delete(Event $event, EntityInterface $entity)
    {
        $field = $entity->getField();
        $options = $field['_options'];
        if (isset($options['xunsearch'])) {
            $xunsearch = new Xunsearch($options['xunsearch']);
            $id = (string) $entity->getId();
            $xunsearch->delete($id);
        }
    }
}
